import editForm from "../form.vue";

import { message } from "@/utils/message";

import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { isAllEmpty } from "@pureadmin/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AppUtil from "@/utils/AppUtil";
export function useMenu() {
  const form = reactive({
    title: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  /**0=目录，10=菜单，20=按钮 */
  const getMenuType = (type, text = false) => {
    switch (type) {
      case 10:
        return text ? "菜单" : "primary";

      case 0:
        return text ? "目录" : "danger";
      case 20:
        return text ? "按钮" : "info";
    }
  };

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{row.menuName}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "type",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getMenuType(row.type)} effect="plain">
          {getMenuType(row.type, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "path",
      cellRenderer: ({ row }) => row.redirect || row.path
    },
    {
      label: "组件路径",
      prop: "component",
      formatter: ({ path, component }) =>
        isAllEmpty(component) ? path : component
    },

    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    // loading.value = true;
    // const { data } = await getMenuList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    // let newData = data;
    // if (!isAllEmpty(form.title)) {
    //   // 前端搜索菜单名称
    //   newData = newData.filter(item =>
    //     transformI18n(item.title).includes(form.title)
    //   );
    // }
    // dataList.value = handleTree(newData); // 处理成树结构
    AppUtil.request(
      {
        url: "/api/v1/menus/treeSelect",
        method: "get"
      },
      res => {
        console.log("listUrl", res);
        dataList.value = res.data;
        res.data.map(val => {
          if (val.icon.indexOf(":") == -1) {
            val.icon = "ep:home-filled";
          }
        });
        // newFormInline.higherMenuOptions=   formatHigherMenuOptions(res.data.records);
        // pData.dataArr = res.data.data;
        // pData.pagination.total = res.data.total;
        // pData.pagination.currentPage = res.data.current_page;
      },
      b => (loading.value = false)
    );
  }

  function formatHigherMenuOptions(treeList) {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].title = treeList[i].menuName;
      formatHigherMenuOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          parentTreeCode: row?.parentTreeCode ?? "",
          menuName: row?.menuName ?? "",
          path: row?.path ?? "",
          viewSort: row?.viewSort ?? 99,
          icon: row?.icon ?? "",
          deletable: row?.deletable ?? 0,
          sid: row?.sid ?? "",
          permission: row?.permission ?? "",
          /**0=目录，10=菜单，20=按钮 */
          type: row?.type ?? 0,

          visible: row?.visible ?? 0,
          higherMenuOptions: formatHigherMenuOptions(dataList.value)

          // enterTransition: row?.enterTransition ?? "",
          // leaveTransition: row?.leaveTransition ?? "",
          // activePath: row?.activePath ?? "",
          // auths: row?.auths ?? "",
          // frameSrc: row?.frameSrc ?? "",
          // frameLoading: row?.frameLoading ?? true,
          // keepAlive: row?.keepAlive ?? false,
          // hiddenTag: row?.hiddenTag ?? false,
          // showLink: row?.showLink ?? true,
          // showParent: row?.showParent ?? false
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        let data = {
          menuName: curData?.menuName ?? "",
          path: curData?.path ?? "",
          viewSort: curData?.viewSort ?? 99,
          icon: curData?.icon ?? "",
          deletable: curData?.deletable ?? 0,

          permission: curData?.permission ?? "",
          /**0=目录，10=菜单，20=按钮 */
          type: curData?.type ?? 0,

          visible: curData?.visible ?? 0
        };
        if (curData.parentTreeCode) {
          data.parentTreeCode = curData.parentTreeCode;
        }
        function chores() {
          console.log("curData1", curData);
          AppUtil.request(
            {
              url: curData.sid
                ? "/api/v1/menus/" + curData.sid
                : "/api/v1/menus",
              method: curData.sid ? "put" : "post",
              data: data
            },
            res => {
              message(`您${title}了菜单名称为${curData.menuName}的这条数据`, {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
          );
        }
        FormRef.validate(valid => {
          if (valid) {
            // console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    AppUtil.request(
      {
        url: "/api/v1/menus/delete",
        method: "put",
        data: {
          sidList: [row.sid]
        }
      },
      res => {
        message(`您删除了菜单名称为${row.menuName}的这条数据`, {
          type: "success"
        });
        onSearch();
      }
    );
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange
  };
}
